package me.ingxin.android.permission2

import android.content.Context
import android.os.Build
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import androidx.fragment.app.FragmentManager

/**
 * Created on 2023/7/1 by yin
 */
class PermissionX private constructor(
    private val context: Context, private val fragmentManager: FragmentManager
) {

    fun permissions(vararg permissions: String): PermissionMediator {
        val normalPermissionSet = LinkedHashSet<String>()
        val specialPermissionSet = LinkedHashSet<String>()
        for (permission in permissions) {
            if (permission in supportSpecialPermissions) {
                specialPermissionSet.add(permission)
            } else {
                normalPermissionSet.add(permission)
            }
        }

        val osVersion = Build.VERSION.SDK_INT
        val targetSdkVersion = context.targetSdkVersion

        //后台定位比较特殊，以下情况可以当做普通权限处理
        if (PERMISSION_ACCESS_BACKGROUND_LOCATION in specialPermissionSet) {
            //运行在android10 或者 运行在android11上但app的targetSdk低于android11的应用
            if (osVersion == Build.VERSION_CODES.Q || (osVersion == Build.VERSION_CODES.R && targetSdkVersion < Build.VERSION_CODES.R)) {
                specialPermissionSet.remove(PERMISSION_ACCESS_BACKGROUND_LOCATION)
                normalPermissionSet.add(PERMISSION_ACCESS_BACKGROUND_LOCATION)
            }
        }

        if (PERMISSION_POST_NOTIFICATIONS in specialPermissionSet) {
            //android13上，通知权限变成了普通权限
            if (osVersion >= Build.VERSION_CODES.TIRAMISU && targetSdkVersion >= Build.VERSION_CODES.TIRAMISU) {
                specialPermissionSet.remove(PERMISSION_POST_NOTIFICATIONS)
                normalPermissionSet.add(PERMISSION_POST_NOTIFICATIONS)
            }
        }

        return PermissionMediator(
            context, fragmentManager, normalPermissionSet.toList(), specialPermissionSet.toList()
        )
    }

    companion object {

        @JvmStatic
        fun with(fragment: Fragment): PermissionX =
            PermissionX(fragment.requireContext(), fragment.childFragmentManager)

        @JvmStatic
        fun with(activity: FragmentActivity): PermissionX =
            PermissionX(activity, activity.supportFragmentManager)

    }


}